﻿#include "counter.h"
#include "ui_counter.h"
#include <QDebug>
Counter::Counter(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Counter)
{
    ui->setupUi(this);
    this->timer.setInterval(1000);
    connect(&this->timer,&QTimer::timeout,this,&Counter::onTimeout);
    this->countdown = false;
}

Counter::~Counter()
{
    delete ui;
}

void Counter::on_radioButton_clicked()
{

    if(ui->radioButton->isChecked()){
        this->countdown = true;
        this->step = -1;

    }else{
        this->countdown = false;
        this->step = 1;
    }
    ui->spinBox_min->setEnabled(this->countdown);
    ui->spinBox_sec->setEnabled(this->countdown);
}

void Counter::onTimeout()
{

    this->restTime+=this->step;
    if(this->countdown){
        if(restTime<=0){
            this->timer.stop();
            this->timer.setInterval(1000);
            if(this->tts.state()==QTextToSpeech::Ready){
                tts.say(tr("Time out"));
                tts.say(tr("Time out"));
                tts.say(tr("Time out"));
                return;
            }
        }
        ui->lcdNumber->display(QString("%1.%2").arg(restTime/60).arg(restTime%60));
    }else{
        restTime++;
        ui->lcdNumber->display(QString("%1.%2").arg(restTime/60).arg(restTime%60));
    }
}

void Counter::on_pushButton_start_clicked()
{
    if(this->countdown)this->restTime = ui->spinBox_min->value()*60+ui->spinBox_sec->value();
    else this->restTime =0;
    ui->lcdNumber->display(QString("%1.%2").arg(restTime/60).arg(restTime%60));
    ui->pushButton_clear->setEnabled(false);
    ui->pushButton_pause->setEnabled(true);
    ui->pushButton_start->setEnabled(false);
    this->timer.start();
}

void Counter::on_pushButton_pause_clicked()
{
    timer.stop();
    ui->pushButton_clear->setEnabled(true);
    ui->pushButton_pause->setEnabled(false);
    ui->pushButton_start->setEnabled(true);
}

void Counter::on_pushButton_clear_clicked()
{
    timer.stop();
    timer.setInterval(1000);
    ui->lcdNumber->display("0.0");
}
